import java.util.Scanner;

/**
 * @author yu
 * @date 2025年04月19日 16:17
 */
public class _02_LinkedList_03_206reverseList {
    public ListNode reverseList(ListNode head) {
        ListNode prev = null;//为null不是 new ListNode(); 这样还是创建了一个新的
        ListNode cur = head;
        ListNode temp = null;
        while (cur != null) {
            temp = cur.next;// 保存下一个节点
            cur.next = prev;
            prev = cur;
            cur = temp;
        }
        return prev;
    }

    // 根据数组创建链表
    public ListNode createLinkedList(int[] arr) {
        if (arr.length == 0) {
            return null;
        }
        ListNode head = new ListNode(arr[0]);
        ListNode current = head;
        for (int i = 1; i < arr.length; i++) {
            current.next = new ListNode(arr[i]);
            current = current.next;
        }
        return head;
    }

    // 打印链表
    public void printLinkedList(ListNode head) {
        ListNode current = head;
        while (current != null) {
            System.out.print(current.val + " ");
            current = current.next;
        }
        System.out.println();
    }

    public static void main(String[] args) {
        _02_LinkedList_03_206reverseList solution = new _02_LinkedList_03_206reverseList();
        Scanner scanner = new Scanner(System.in);

        System.out.println("请输入链表节点的值，用空格分隔：");
        String input = scanner.nextLine();
        String[] valuesStr = input.split(" ");
        int[] values = new int[valuesStr.length];
        for (int i = 0; i < valuesStr.length; i++) {
            values[i] = Integer.parseInt(valuesStr[i]);
        }

        ListNode head = solution.createLinkedList(values);

        System.out.println("原始链表：");
        solution.printLinkedList(head);

        ListNode reversedHead = solution.reverseList(head);

        System.out.println("反转后的链表：");
        solution.printLinkedList(reversedHead);

        scanner.close();
    }
}
